package controller.Operation;

import model.NormalUser;
import model.Record;
import util.BookDao;
import util.RecordDao;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * @Question Borrow
 * @Date 2022/12/19 14:32
 * @Solution
 */
public class Borrow {
    public static void bookBorrow(NormalUser user ,JTable bookTable,DefaultTableModel bookModel,DefaultTableModel recordModel) {
        //检查是否有行被选中
        int row = bookTable.getSelectedRow();
        if(row==-1) {
            JOptionPane.showMessageDialog(null, "请选择需要借阅的书籍!");
            return;
        }
        //获取到该行书籍的id
        int bookId=(int)bookTable.getValueAt(row,0);
        //查看该图书是否可借
        String state=(String) bookTable.getValueAt(row,4);
        if(!state.equals("可借")){
            JOptionPane.showMessageDialog(null, "该书不可借");
            return;
        }
        //选择需要借阅的天数
        int choice = JOptionPane.showOptionDialog(null, "请选择需要借阅的天数", "天数选择对话框",
                JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE,   null, new String[]{"7天","14天","30天"}, "7天");
        //计算到期天数
        int day;
        if(choice==0) {
            day=7;
        } else if(choice==1) {
            day=14;
        } else {
            day=30;
        }
        LocalDateTime start = LocalDateTime.now();
        Date startDate = Date.from( start.atZone( ZoneId.systemDefault()).toInstant());
        LocalDateTime end = start.plusDays(day);
        Date endDate = Date.from( end.atZone( ZoneId.systemDefault()).toInstant());
        //插入记录
        Record record = new Record();
        record.setBookId(bookId);
        record.setUserId(user.getId());
        record.setOutTime(startDate);
        record.setInTime(endDate);
        RecordDao recordDao = new RecordDao();
        recordDao.insert(record);
        //将图书修改为不可借
        BookDao bookDao = new BookDao();
        bookDao.reviseState(bookId,0);
        //刷新
        Show.showByUserIdRecord(recordModel, user.getId());
        Show.showAllBook(bookModel);

        JOptionPane.showMessageDialog(null, "借阅成功！");
    }
}
